package com.mall.controller;

import com.mall.db.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import until.FileUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/file/fc")
public class FileController {
    @Value("${file.root.photo}")
    private String root;
    @Resource(name="fileService")
    private FileService fs;
    @RequestMapping("/fileUpload")
    @ResponseBody
    public Map<String,Object> fileUpload(MultipartFile file) {



        Map<String, Object> map = new HashMap<>();
        try{
            if (file != null) {
                String fileName = file.getOriginalFilename();
                String prefix = fileName.substring(fileName.lastIndexOf("."));
                String newFileName = System.currentTimeMillis() + "" + prefix;
                File f = new File(root, newFileName);
                File f1 = new File(root);
                FileUtil.createDir(f1);
                File f2 = new File(f1, newFileName);
                FileUtil.createFile(f2);
                file.transferTo(f2);

                com.mall.db.domain.File fe=new com.mall.db.domain.File();
                fe.setFileSize(file.getSize());
                fe.setOldFilename(fileName);
                fe.setNewFilename(newFileName);
                fe.setSuffix(prefix);
                fe.setPath(f2.getAbsolutePath());




                //执行新增
                boolean b=fs.save(fe);
                if(b){
                    map.put("file",fe);
                    map.put("is",true);
                }else {
                    map.put("file","");
                    map.put("is",false);
                }

            }
        }catch (IOException e){
            map.put("file","");
            map.put("is",false);
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping("/showImg/{id}")
    public void  showImg(@PathVariable(name = "id") int id, HttpServletResponse res){
        try {
            com.mall.db.domain.File f=fs.getById(id);
            File  f2=new File(f.getPath());
            FileInputStream fis=new FileInputStream(f2);
            OutputStream fos=res.getOutputStream();
            byte bs[]=new byte[1024];
            int i=0;
            while ((i=fis.read(bs))>0){
                fos.write(bs,0,i);
            }
            fos.close();
            fis.close();
        }catch (IOException e){
            e.printStackTrace();
        }

    }

}
